<script setup>
import api from '../../api/user.js';
import {ref,onMounted} from "vue";
import {ElMessageBox} from "element-plus";
import lodash from 'lodash';

//定义绑定的数据
//绑定表格中的数据
const tableData=ref([]);

const total=ref(0);
//定义对话框的显示状态
const editWinVisible=ref(false);
//定义新增对话框的显示状态
const addWinVisible=ref(false);
//绑定查询数据
const searchObj=ref({
  current:1,
  size:10,
  username:'',
  phone:'',
  email:'',
  idCard:'',
  avatar:''
});

//要修改或新增的数据
const obj=ref({
  username:'',
  phone:'',
  email:'',
  idCard:'',
  avatar:''// 预定义 photo，避免响应式失效
});

const search = async() => {
  var result=await api.page(searchObj.value);
  console.log('接口返回结果：', result);
  tableData.value= result.records||[];
  total.value=result.total||0;
}
//页面加载后要挂载的数据
onMounted(async ()=> {
  search();
});
//定义方法

//  新增：获取本地存储的 Token（登录时存入），用于上传请求头
const getToken = () => {
  return localStorage.getItem('token') || '';
};

//  新增：限制文件类型（仅图片）和大小（≤2MB）
const beforeAvatarUpload = (file) => {
  // 限制文件类型：仅 jpg、jpeg、png、gif
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件（支持 jpg、jpeg、png、gif）！');
    return false;
  }
  // 限制文件大小：≤2MB（1MB=1024KB，1KB=1024B）
  const isLt2M = file.size / 1024 / 1024 <= 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！');
    return false;
  }
  return true; // 验证通过，允许上传
};


const handleUploadSuccess = (response, file, row) => {
  // 直接更新当前行的 photo 字段
  if (row) {
    // 编辑场景：更新表格行的 photo
    row.avatar = response.data;
    obj.value.avatar = response.data;// 编辑时同步更新 obj，避免提交时丢失
  } else {
    // 新增场景：直接赋值给 obj.photo
    obj.value.avatar = response.data;
  }
}

const handleSizeChange=(val)=>{
  searchObj.value.size = val; // 更新每页条数
  search();
}
const handleCurrentChange=(val)=>{
  searchObj.value.current = val; // 更新每页条数
  search();
}
//修改
const editCancel = () => {
  obj.value={username:'',
    phone:'',
    email:'',
    idCard:'',
    avatar:'' }; //清空数据
  editWinVisible.value=false;  //关闭对话框
}

const editCommit = async() => {
  await api.edit(obj.value);  //提交修改数据
  search();  //刷新表格
  editWinVisible.value=false;  //关闭编辑对话框
}
//增加
const addCancel = () => {
  obj.value={username:'',
    phone:'',
    email:'',
    idCard:'',
    avatar:'' }; //清空数据
  addWinVisible.value=false;  //关闭对话框
}

const addCommit = async() => {
  // 简单验证：确保必填字段有值
  if (!obj.value.username || !obj.value.phone) {
    ElMessage.warning('用户名和手机号不能为空');
    return;
  }
  await api.add(obj.value);  //提交数据
  search();  //刷新表格
  addWinVisible.value=false;  //关闭增加对话框
  console.log('照片',obj.value);
}


const handlerSearch = () => {
  searchObj.value.current=1;
  search();
}

const handlerAdd = (index, row) => {
  obj.value={username:'',
    phone:'',
    email:'',
    idCard:'',
    avatar:'' };
  addWinVisible.value=true;
  console.log(index, row)
}

const handleSelect = (index, row) => {
  console.log(index, row)
}

const handleEdit = (index, row) => {
  obj.value=lodash.clone(row);
  editWinVisible.value=true;
  console.log(index, row)
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await api.del(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current=1;
        search();
      })
      .catch(() => {

      })
}
</script>


<!--组件，写标签-->
<template>
  <div class="product-container"  style="padding-top: 70px;">
    <div class="page-header">
      <h2>用户列表</h2>
    </div>

    <!--搜索表单-->
    <el-card class="form-container">
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 20px;margin-left: 10px">
    <el-row :gutter="20" align="middle">

      <el-col :span="7" style="text-align: right;">
    <el-form-item label="手机号">
      <el-input v-model="searchObj.phone" placeholder="请输入手机号" clearable />
    </el-form-item>
      </el-col>

      <el-col :span="8" style="text-align: right;">
    <el-form-item label="用户名">
      <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable />
    </el-form-item>
      </el-col>

      <el-col :span="8" style="text-align: right;" :offset="0">
    <el-form-item label="身份证号">
      <el-input v-model="searchObj.idCard" placeholder="请输入" clearable />
    </el-form-item>
      </el-col>

      <el-col :span="12" style="text-align: right;" :offset="0">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
      </el-col>

      <el-col :span="11" style="text-align: left;" :offset="0">
    <el-form-item>
      <el-button type="primary" @click="handlerAdd">新增</el-button>
    </el-form-item>
      </el-col>
    </el-row>
  </el-form>
    </el-card>


<!--    表格内容-->
    <el-card class="table-container" shadow="hover">
  <el-table :data="tableData" style="width: 100%"
            border
            stripe
            :loading="loading"
            highlight-current-row
            @row-click="handleSelect"
  >

<!--    <el-table-column label="头像" width="180">-->
<!--      <template #default="scope">-->
<!--        <div style="display: flex; align-items: center">-->
<!--          <img src="scope.row.photo" />-->
<!--        </div>-->
<!--      </template>-->
<!--    </el-table-column>-->

    <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>

    <el-table-column label="用户名" width="160" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div class="pop-content">
              <p><div>name: {{ scope.row.username }}</div></p>
              <p><div>email: {{ scope.row.email }}</div></p>
            </div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.username }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="头像" :label-width="80" align="center">
      <template #default="scope">
      <el-upload
          class="avatar-uploader"
          action="/api/upload/file"
          :headers="{ Authorization: `Bearer ${getToken()}` }"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="(response, file)=>handleUploadSuccess(response,file,scope.row)"
          placeholder="请输入">
        <!-- :on-success="(response, file)=>handleUploadSuccess(response,file,scope.row)"       上传成功后，更新当前行的photo-->
        <!--        :before-upload="beforeAvatarUpload  提交之前要干什么-->
<!--           :headers="{ Authorization: `Bearer ${getToken()}` }"  携带 Token-->
        <img  v-if="scope.row.avatar&&scope.row.avatar!==''" :src="scope.row.avatar"  style="width:100px; height: 100px; object-fit: cover;" />
        <img  v-else src='@/assets/upload.png'  style="width:100px; height: 100px; object-fit: cover;"/>
      </el-upload>
      </template>
    </el-table-column>

    <el-table-column label="手机号" width="160" align="center">
      <template #default="scope">
          <span class="price-tag">{{ scope.row.phone }}</span>

      </template>
    </el-table-column>

    <el-table-column label="身份证号" width="165" align="center">
      <template #default="scope">
        <span class="price-tag">{{ scope.row.idCard }}</span>

      </template>
    </el-table-column>

    <el-table-column label="邮箱" width="150" align="center">
      <template #default="scope">

          <span class="price-tag">{{ scope.row.email }}</span>

      </template>
    </el-table-column>


    <el-table-column label="处理按钮" align="center">
      <template #default="scope">
        <el-button size="default" type="primary" @click="handleEdit(scope.$index, scope.row)"
                    class="btn-edit">
          编辑
        </el-button>
        <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            class="btn-delete">
          删除
        </el-button>
<!--        <el-button size="mini" type="info" @click="handleSelect(scope.$index, scope.row)"  class="btn-select">-->
<!--          选择-->
<!--        </el-button>-->
      </template>
    </el-table-column>

  </el-table>

<!--      分页控件-->
      <div class="pagination-container">
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.size"
      :page-sizes="[10, 20, 30, 40]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
      </div>
    </el-card>

<!--编辑对话框-->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj" ref="editForm"
             label-width="100px">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

<!--      <el-form-item label="性别" :label-width="100" required>-->
<!--        <el-select-->
<!--            v-model="obj.gender"-->
<!--            placeholder="请选择性别"-->
<!--            style="width: 100%"-->
<!--        >-->
<!--      <el-option-->
<!--          label="男"-->
<!--          value="男"-->
<!--      ></el-option>-->
<!--      <el-option-->
<!--          label="女"-->
<!--          value="女"-->
<!--      ></el-option>-->
<!--      </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="性别" :label-width="100">-->
<!--        <el-input v-model="obj.gender" autocomplete="off" placeholder="请输入"/>-->
<!--      </el-form-item>-->

      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

        <el-form-item label="手机号" :label-width="100">
          <el-input v-model="obj.phone" autocomplete="off" placeholder="请输入"/>
        </el-form-item>

    <el-form-item label="头像" :label-width="100">
    <el-upload
        class="avatar-uploader"
        action="/api/upload/file"
        :headers="{ Authorization: `Bearer ${getToken()}` }"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-success="(response, file) =>handleUploadSuccess(response, file, obj.value)"
        placeholder="请输入">
<!--        :before-upload="beforeAvatarUpload  提交之前要干什么-->

      <img  v-if="obj.avatar" :src="obj.avatar"  style="width:100px; height: 100px; object-fit: cover;" />
      <img  v-else src='@/assets/upload.png'  style="width:100px; height: 100px; object-fit: cover;"/>
    </el-upload>
    </el-form-item>

      <el-form-item label="身份证号" :label-width="100">
        <el-input v-model="obj.idCard" autocomplete="off" placeholder="请输入"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

<!--  增加对话框-->
  <el-dialog v-model="addWinVisible" title="新增" width="500">
    <el-form :model="obj" ref="addForm"
             label-width="100px">

      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

      <el-form-item label="手机号" :label-width="100">
        <el-input v-model="obj.phone" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

      <el-form-item label="身份证号" :label-width="100">
        <el-input v-model="obj.idCard" autocomplete="off" placeholder="请输入"/>
      </el-form-item>

<!--      <el-form-item label="性别" :label-width="100">-->
<!--        <el-input v-model="obj.gender" autocomplete="off" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="性别" :label-width="100" required>-->
<!--        <el-select-->
<!--            v-model="obj.gender"-->
<!--            placeholder="请选择性别"-->
<!--            style="width: 100%"-->
<!--        >-->
<!--          &lt;!&ndash; 固定下拉选项：男、女 &ndash;&gt;-->
<!--          <el-option-->
<!--              label="男"-->
<!--              value="男"-->
<!--          ></el-option>-->
<!--          <el-option-->
<!--              label="女"-->
<!--              value="女"-->
<!--          ></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="真实姓名" :label-width="100">-->
<!--        <el-input v-model="obj.real_name" autocomplete="off" />-->
<!--      </el-form-item>-->

      <el-form-item label="头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :headers="{ Authorization: `Bearer ${getToken()}` }"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="(response, file)=>handleUploadSuccess(response,file,undefined)"
            placeholder="请输入">
          <!--        :before-upload="beforeAvatarUpload  提交之前要干什么-->

          <img  v-if="obj.avatar" :src="obj.avatar"  style="width:100px" />
          <img  v-else src='@/assets/upload.png'  style="width:100px"/>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>


<style scoped>

/* 优化样式，避免图片拉伸、按钮间距异常 */
.avatar-uploader {
  cursor: pointer;
}
.price-tag {
  color: #666;
}
.btn-edit, .btn-delete, .btn-select {
  margin-right: 8px;
}
.pagination-container {
  margin-top: 16px;
  text-align: right;
}
/* 页面容器样式 */
.product-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%; /* 继承 el-main 高度，确保内容不足时占满 */
  height: auto; /* 清除原 calc(100vh - 40px)，避免高度冲突 */
  box-sizing: border-box; /* 防止 padding 导致溢出 */
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #1f2329;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 5px 0 0;
  color: #86909c;
  font-size: 14px;
}

/* 表单容器样式 */
.form-container {
  margin-bottom: 20px;
  border-radius: 6px;
  overflow: hidden;
}

.search-form {
  padding: 15px 0;
}

/* 输入框样式 */
.input-with-icon {
  width: 100%;
}

/* 按钮区域样式 */
.action-buttons {
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

/* 表格容器样式 */
.table-container {
  border-radius: 6px;
  overflow: hidden;
  height: auto; /* 清除固定高度，由表格内容撑开 */
}

/* 商品名称样式 */
.product-name {
  color: #1890ff;
  cursor: pointer;
  transition: color 0.2s;
}

.product-name:hover {
  color: #096dd9;
  text-decoration: underline;
}

/* 价格标签样式 */
.price-tag {
  color: #262525;
  font-weight: 500;
}

/* 图片容器样式 */
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.1);
}

.no-image {
  color: #86909c;
  font-size: 12px;
}

/* 操作按钮样式 */

.btn-edit {
  margin-right: 5px;
  text-align: center;
}


.btn-delete {
  margin-right: 5px;
  text-align: center;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  padding-right: 10px;
}

/* 弹出内容样式 */
.pop-content p {
  margin: 5px 0;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .el-col {
    margin-bottom: 10px;
  }

  .action-buttons {
    margin-top: 10px;
  }
}

@media (max-width: 768px) {
  .product-container {
    padding: 10px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    width: auto !important;
  }
}
</style>